#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@File    : /coruntine.py
@Time    : 2021-05-14 16:45:50
@Author  : Gray Snail
@Version : 1.0
@Contact : shtao2011@sina.com
@License : Copyright (c) 2021 Gray Snail
@Desc    : None

https://cloud.tencent.com/developer/article/1552281
'''


import asyncio
import random
import time


'''
协程 coroutine: async 修饰的函数返回值

协程必须封装成task，才能避免阻塞，封装的两种方法:
    1. task = loop.create_tash(coroutine)
    2. task = asyncio.ensure_future(coroutine)

task添加回调函数：
    task.add_done_callback()

'''


async def say(name, hour):
    print(f'{name} 等待 {hour}秒')
    await asyncio.sleep(hour)


name_list = ['Chancey', 'Wanger', 'Mary', 'SuXin']
now = lambda: time.time()


if __name__ == '__main__':
    loop = asyncio.get_event_loop()

    start = now()
    coroutine_list = []
    for i in range(1, 5):
        name = name_list[i - 1]
        hour = i
        coroutine_list.append(say(name, hour))

    # 创建task
    task_list = [loop.create_task(item) for item in coroutine_list]

    for task in task_list:
        loop.run_until_complete(task)

    print('耗时: %.02f' % (now() - start))
